<template>
    <Modal 
        v-model="showQuickCreateModal"
        title="快速构建"
        width="1200px"
        :mask-closable="false"
        @on-visible-change="visibleChange">
        <!-- 渗透、护网不需要设置接入机器 -->
        <!-- <Form ref="accessMachineForm" :model="accessMachineForm" :label-width="80" :rules="accessMachineRules" v-if="type === 4">
            <FormItem label="镜像" prop="image">
                <Select filterable v-model="accessMachineForm.image" placeholder="请选择镜像" filterable clearable @on-change="getImageDetail">
                    <Option v-for="item in imageList" :key="item.id" :value="item.id" :title="item.imageName" 
                        :disabled="item.haveUsers == 0">{{item.imageName}}</Option>
                </Select>
            </FormItem>
            <FormItem label="配额" prop="flavor">
                <Select filterable v-model="accessMachineForm.flavor" placeholder="请选择配额" filterable clearable>
                    <Option v-for="item in showFloverList" :key="item.id" :value="item.id" :title="item.flavorname">{{item.flavorname}}</Option>
                </Select>
            </FormItem>
            <FormItem label="数量" prop="numbers">
                <input-number :min="1" :max="10000" v-model="accessMachineForm.numbers" style="width: 350px;"></input-number>个
            </FormItem>
            <FormItem label="前缀" prop="prefix">
                <Input v-model="accessMachineForm.prefix" disabled></Input>
            </FormItem>
            <FormItem label="接入机器" prop="vmDate">
                <div>
                    <Tag class="select-tag" v-for="(item, index) in accessMachineList" :key="item.id" :name="item.name" type="dot" color="primary"
                        closable @on-close="removeSelectData('machine', index)">{{ item.name }}</Tag>
                </div>
            </FormItem>
            <span class="error-text">{{noAccessMachine ? '接入机器不能为空' : '' }}</span>
            <FormItem>
                <Button @click="commitSelectData('machine')" long type="warning" ghost>添加接入机器</Button>
            </FormItem>
        </Form> -->
        <div class="bold" style="margin-bottom:10px" v-if="type==5&&hwType!=3">
            <span style="font-weight: 700;">是否接入机器：</span>
            <i-Switch v-model="vmInEnable" @on-change="vmTeamOrPerson = 'team'"/>
        </div>
        <!-- 选择 按团队分配还是按成员分配 -->
        <div class="bold" style="margin-bottom:10px" v-if="vmInEnable">
            接入机器分配方式：
            <RadioGroup v-model="vmTeamOrPerson">
                <Radio label="team">按团队分配</Radio>
                <Radio label="person">按成员分配</Radio>
            </RadioGroup>
        </div>
        <Form :label-width="80">
            <!-- <div style="margin-bottom: 5px;" v-if="type == 5 && hwType == 2">
                <span style="font-weight: 700;">允许虚拟接入：</span>
                <i-Switch v-model="allowVirtualAccess" />
            </div> -->
            <div class="bold">
                已选团队
                <Tag color="purple">{{checkTeamList.length}}</Tag>
                <span class="error-text">{{noTeam ? '所选团队不能为空' : (showDuplicateNameTip ? `${repeatTeam.join(',')}中存在相同成员` : '')}}</span>
            </div>
            <!-- <div class="tag-list">
                <Tag class="select-tag" v-for="item in checkTeamList" :key="item.id" :name="item.name" 
                    closable @on-close="removeTeam([],item)" type="dot" :color="item.color">{{ item.name }}</Tag>
                <div style="clear: both;"></div>
            </div> -->
            <Input v-model="teamName" placeholder="团队名称" style="width: 180px; margin-bottom: 12px;" clearable @on-change="getDataBounce"></Input>
            <TableList 
                :columns="teamColumns" 
                :data="teamList" 
                :loading="loadingTable"
                :total="teamTotal"
                :size="pageSize"
                :page="pageIndex"
                class="mb40"
                :disabled="(team) => team.userList.length == 0"
                showSelectTag
                :selection.sync="checkTeamList"
                @change-page="teamsPageNum"
                @change-size="teamsSizeNum"
            ></TableList>
        </Form>
        <Form ref="questionForm" :model="questionForm" :label-width="80" :rules="questionRules" v-if="type === 4">
            <div class="bold">
                已选题目{{stMode === 0 ? '（顺序答题，题目添加顺序决定了答题顺序）' : ''}}
                <Tag color="purple">{{checkQuestionList.length}}</Tag>
                <span class="error-text">{{noQuestion ? '所选题目不能为空' : '' }}</span>
            </div>
            <!-- <div class="tag-list">
                <Tag class="select-tag" v-for="item in checkQuestionList" :key="item.chaId" :name="item.name" type="dot" color="primary"
                    closable @on-close="removeQuestion([], item)">
                    {{item.name}}
                </Tag>
                <div style="clear: both;"></div>
            </div> -->
            <Input v-model.trim="questionParams.name"  placeholder="题目名称" style="width: 180px; margin-bottom: 12px;" clearable @on-change="challsPageNum(1)" class="mr16"/>
            <Select filterable v-model="questionParams.needEnv" style="width: 180px; margin-bottom: 12px;" @on-change="challsPageNum(1)">
                <Option value="all">全部(是否需要环境)</Option>
                <Option value="true">需要</Option>
                <Option value="false">不需要</Option>
            </Select>
            <Select filterable v-model="questionParams.category"  style="width: 180px; margin-bottom: 12px;" placeholder="类型"
                @on-change="challsPageNum(1)">
                <Option value="all">全部(题目类型)</Option>
                <Option :value="category.dictname" v-for="category in questionTypeList" :key="category.dictname" 
                    :title="category.dictname">{{category.dictname}}</Option>
            </Select>
            <Select filterable v-model="questionParams.flagType" style="width: 180px; margin-bottom: 12px;" @on-change="challsPageNum(1)">
                <Option value="all">全部(验证类型)</Option>
                <Option value="1">静态Flag</Option>
                <Option value="0">固定Flag</Option>
                <Option value="3">提交报告</Option>
            </Select>
            <TableList 
                :columns="challsCol" 
                :data="questionList"  
                class="mb40"
                :total='questionTotal'
                :page.sync="questionParams.pageIndex"
                :size.sync="questionParams.pageSize"
                @change-page="challsPageNum"
                @change-size="challsSizeNum"
                showSelectTag
                selectKey="chaId"
                :selection.sync="selectQuestions"></TableList>
            <!-- <Page :total='questionTotal' show-total show-elevator show-sizer :page-size="questionParams.pageSize" :current="questionParams.pageIndex"
                    @on-page-size-change="challsChangeSize" @on-change="challsPageNum" class="mt30-right" /> -->
        </Form>
        <div slot="footer">
            <Button @click="hide">取消</Button>
            <Button @click="quickCreat" type="primary" :loading='saveLoading'>确定</Button>
        </div>
    </Modal>
</template>

<script>
import { getGroupHasUsers } from '@/api/company'
import { queryExperGroups, getExperGroupsUsers } from '@/api/users'
import { debounce, parseJson } from '@/libs/utils'
import { getallImage, getallFlavor, queryCtfList } from '@/api/question'
import { quickCreateContest, quickCreateContestMacth, modifyScene, batchAddTarget } from '@/api/drill_compete'
import { getDetailByID } from '@/api/image'
import { experType } from '@/api/dict'

export default {
    name:'qiuckCreate',
    props: {
        type: { // 场景类型，默认渗透演练，本组件暂支持渗透、护网两种类型
            type: Number,
            default: 4 // 0:对抗演练、1:攻防赛、2:夺旗赛、3:知识赛、4:渗透演练、5:护网演练、6:应急防御演练、7:综合演练
        },
        hwType: {
            type: Number // 0-老护网 1-实网演练 2-众测演练 4-仿真要手动改成3
        }
    },
    data() {
        const validateNumbers = (rule, value, callback) => { // 1~10000
            if (Number.isInteger(value)) {
                if (value >= 1 && value <= 10000) {
                    callback()
                } else {
                    callback('设值范围：1~10000')
                }
            } else {
                callback('请输入整数')
            }
        }
        return {
            drillInfo: {},
            saveLoading: false, // 快速构建确认按钮的loading状态
            currentImageInfo: {}, // 当前选中的镜像详情
            questionTypeList: [], // 题目类型
            challsCol: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '题目名称',
                    key: 'name',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                },

                {
                    title: '题目类型',
                    key: 'category',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true
                },
                {
                    title: '验证类型',
                    key: 'flagType',
                    align: 'center',
                    render:(h,params) => {
                        return h('span',this.$options.filters.filterFlagType(params.row.flagType))
                    }
                },
                {
                    title: '是否需要部署',
                    key: 'needEnv',
                    align: 'center',
                    render: (h, params) => {
                        return h('span', {
                            style: {
                                color: params.row.needEnv == 'true' ? 'green' : 'red',
                            }
                        },
                        this.needEnvFilter(params.row.needEnv))
                    }
                },
                {
                    title: '题目分数',
                    key: 'score',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                },
                {
                    title: '描述',
                    key: 'description',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                },
                {
                    title: '操作',
                    key: 'os',
                    align: 'center',
                    ellipsis: true,
                    render: (h, params) => {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small',
                                    disabled:this.checkQuestionList.map(cha=>cha.chaId).includes(params.row.chaId) 
                                        || params.row.category === '安全运维'
                                        || params.row.answers.length > 1
                                },
                                style: {
                                    marginRight: '5px',
                                },
                                on: {
                                    click: () => {
                                        this.selectQuestion('',params.row);
                                    }
                                }
                            }, '添加')
                        ])
                    }
                }
            ],
            teamColumns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '团队名称',
                    key: 'name',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                },
                {
                    title: '团队成员数',
                    key: 'userNum',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                },
                {
                    title: '团队成员',
                    key: 'userNameList',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                    filter:(userNameList) => {
                        return userNameList.join(',')
                    }  
                },
                {
                    title: '创建者',
                    key: 'creatorName',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                },
                {
                    title: '操作',
                    key: 'os',
                    align: 'center',
                    ellipsis: true,
                    render: (h, params) => {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small',
                                    disabled: this.checkTeamList.map(item => item.id).includes(params.row.id) || params.row.userIdList.length === 0
                                },
                                on: {
                                    click: () => {
                                        this.selectTeam('',params.row)
                                    }
                                }
                            }, '添加')
                        ])
                    }
                }
            ],
            loadingTable: false, // 加载表单
            teamTotal: 0, // 总团队数
            pageIndex: 1, // 当前页
            pageSize: 10, // 分页大小
            teamName: '', // 搜索条件，团队名称
            imageList: [], // 镜像列表
            questionList: [], // 题目列表
            questionTotal: 0,
            flavorList: [], // 配额列表
            teamList: [], // 团队列表
            checkTeamList: [], // 已选中的团队
            accessMachineList: [], // 添加的接入机器
            selectQuestions: [], // 已添加的题目
            accessMachineForm: { // 接入机器表单对象
                image: '',
                flavor: '',
                numbers: 1,
                prefix: '接入机器1',
                vmDate: []
            },
            accessMachineNum: 1,
            accessMachineRules: { // 接入机器验证规则
                image: [
                    { required: true, message: '请选择镜像', trigger: 'change' }
                ],
                flavor: [
                    { required: true, message: '请选择配额', trigger: 'change' },
                ],
                numbers: [
                    { required: true, type: 'number', message: '请输入数量', trigger: 'change' },
                    { validator: validateNumbers, trigger: 'change' }
                ],
                prefix: [
                    {required: true, message: '请输入前缀', trigger: 'change' }
                ]
            },
            questionForm: { // 题目表单对象
                question: '',
                image: '',
                flavor: '',
                prefix: '',
                numbers: 1,
                questionDate: []
            },
            questionRules: { // 题目验证规则
                question: [
                    { required: true, message: '请选择题目', trigger: 'change' }
                ],
                prefix: [
                    { required: true, message: '请输入前缀', trigger: 'change' }
                ],
                numbers: [
                    { required: true, type: 'number', message: '请输入数量', trigger: 'change' },
                    { validator: validateNumbers, trigger: 'change' }
                ]
            },
            repeatTeam: [], // 有成员重复的团队
            noAccessMachine: false,
            noQuestion: false,
            noTeam: false,
            showDuplicateNameTip: false, // 团队是否有成员重复
            showQuickCreateModal: false, // 控制是否显示模态框，默认隐藏
            questionParams: {
                pageIndex: 1, // 当前页
                pageSize: 10, // 分页大小
                name: '',
                needEnv: 'all',
                category: 'all',
                flagType: 'all'
            },
            allowVirtualAccess: false, // 允许虚拟接入
            vmInEnable:this.type == 4 ? true : false,
            vmTeamOrPerson:'team'
        }
    },
    filters:{
        // 格式化状态码转换
        filterFlagType(type){
            if(type == 0){
                return '固定Flag'
            }else if(type == 1){
                return '静态Flag'
            }else if(type == 2){
                return 'Checker'
            }else if(type == 3){
                return '提交报告'
            }else{
                return '未定义类型'
            }
        }
    },
    mounted() {
        this.$nextTick(() => {
            if (this.type === 4) {
                this.getQuestionType()
            }
        })
    },
    watch: {
        accessMachineList(list) {
            this.noAccessMachine = list.length === 0
        },
        checkQuestionList(list) {
            this.noQuestion = list.length === 0
        },
        checkTeamList(list) { // 选中的团队改变时，存在重复用户，需要查出是哪些团队存在重复信息
            let allSelUserIds = [...list.map(team => team.userIdList).flat()];
            if(this.haveDuplicateMembers(allSelUserIds)){
                this.showDuplicateNameTip = true;
            }else{
                this.showDuplicateNameTip = false;
            }
            if (this.showDuplicateNameTip) {
                let retList = []
                list.forEach((team, index) => { // 双层遍历，将有重复用户的团队查找出来
                    for (let i = index + 1, length = list.length; i < length; i++) {
                        let userIdList = team.userIdList
                        let nextUserIds = list[i].userIdList
                        if ([...new Set(userIdList.concat(nextUserIds))].length !== (userIdList.length + nextUserIds.length)) { // 去重后长度不等，则数据有重复
                            retList.push(`${team.name}`, `${list[i].name}`)
                        }
                    }
                })
                let repeatTeam = [...new Set(retList)]
                list.forEach(item => {
                    if (repeatTeam.includes(item.name)) {
                        item.color = 'error'
                    } else {
                        item.color = 'primary'
                    }
                })
                this.repeatTeam = repeatTeam
            } else {
                list.forEach(item => item.color = 'primary')
            }
            this.noTeam = list.length === 0
        }
    },
    computed: {
        showFloverList() { // 过滤掉不适用的配额
            let imageInfo = this.currentImageInfo
            if (imageInfo.minram && imageInfo.mindisk) {
                return this.flavorList.filter(flover => Number(flover.ram) >= imageInfo.minram && Number(flover.rootdisk) >= imageInfo.mindisk)
            } else {
                return this.flavorList
            }
        },
        extension() {
            return parseJson(this.drillInfo.extension)
        },
        stMode() {
            return this.extension.stMode || 0
        },
        checkQuestionList(){
            return this.selectQuestions.map(data => {
                return {
                    "chaId": data.chaId,
                    "name": data.name,
                    "imageRef": data.imageId,
                    "flavorRef": data.flavorRef,
                    "hidden": 0,
                    "needEnv": data.needEnv,
                    "data": data
                }
            })
        },
        hwExtentionType(){
            return this.extension.hwExtentionType || 0
        },
        quickType(){
            // this.hwType 4 仿真
            return Number(this.type) === 5 &&  Number(this.hwType) == 4  
            ?'simulation_network_exercise':Number(this.type) === 5 && Number(this.hwType) != 4 
            ?"protect_network_exercise" : "break_through"
        },
    },
    methods: {
        // 获取题目类型
        getQuestionType() {
            experType('questionType').then(({ code, message, attribute = [] }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                } else {
                    this.questionTypeList = ((attribute.attribute[0] || {}).dictEntryList || []).map(item => {
                        return {
                            dictname: unescape(item.dictname)
                        }
                    })
                }
            }).catch(() => {
                this.$Message.error('获取题目类型异常')
            })
        },
        // 选择题目并添加
        selectQuestion(selection,row){
            this.selectQuestions.push(row)
            // this.$refs.teamTable.selectItem(item);
            return
            let questionList = []
            if(!row){ // 全选
                selection.forEach(ques => {
                    let selQuesIds = this.checkQuestionList.map(item => item.chaId);
                    if(!selQuesIds.includes(ques.chaId)){ // 添加不包含的题目
                        let listQues = this.questionList.filter(chall => chall.chaId == ques.chaId);
                        if(listQues.length > 0){
                            listQues[0]._checked = true;
                        }
                        questionList.push({row:ques})
                    }
                })
            }else{
                let listQues = this.questionList.filter(chall => chall.chaId == row.chaId);
                if(listQues.length > 0){
                    // listQues[0]._checked = true;
                    this.$set(listQues[0],'_checked',true)
                    questionList.push({row})
                }
            }
            // 遍历后一次赋值
            let checkQuestionList = []
            questionList.forEach(data => {
                let chall = {
                    "chaId": data.row.chaId,
                    "name": data.row.name,
                    "imageRef": data.row.imageId,
                    "flavorRef": data.row.flavorRef,
                    "hidden": 0,
                    "needEnv": data.row.needEnv,
                    "data": data.row
                }
                checkQuestionList.push(chall)
                
            })
            this.checkQuestionList.push(...checkQuestionList)
        },
        // 转义“是否需要部署”的状态码为中文
        needEnvFilter(val) {
            return val === 'true' ? '需要' : '不需要'
        },
        // 快速构建
        quickCreat() {
            const extIObj =  JSON.parse(this.drillInfo.extension)
            console.log(extIObj);
            const keys = Object.keys(extIObj);
            const vpnKeys = keys.filter(key => key.startsWith("vpn"));
            // 已经没有接入机器了
            // if (this.type === 4 && this.accessMachineList.length === 0) {
            //     this.$Message.error('接入机器不能为空')
            //     return
            // }
            if (this.type === 4 && this.checkQuestionList.length === 0) {
                this.$Message.error('所选题目不能为空')
                return
            }
            if (this.checkTeamList.length === 0) {
                this.$Message.error('所选团队不能为空')
                return
            }
            if (this.showDuplicateNameTip) {
                this.$Message.error('团队成员重复')
                return
            }
            if (this.type === 5 && this.checkTeamList.some(item => item.userIdList.length === 0)) {
                this.$Message.error('所选团队存在成员为空的情况，请处理')
                return
            }
            this.saveLoading = true
            let sceneOptions = {
                "contestId": this.drillInfo.id,
                "contestName": this.drillInfo.name,
                "hwChangeIp": Number(this.extension.hwChangeIp) === 1,
                "hwDeployMode": Number(this.extension.deployMode)  === 2 ? "route" : "tunnel",
                "partyEnable": false,
                "spareEnvNum": 0,
                "targetCount": 200,
                "teams": [],
                "contestPapers": [],
                "type": this.quickType,
                "pmInEnable": false,
                "newHw":vpnKeys[0],
                "publicSubnetId":extIObj.publicSubnetId
            }
            // hwType 1 新护网  2众测   4 仿真
            if(this.type==5&&this.hwType==3){
                sceneOptions.rcFlag = 'rc'
                delete sceneOptions.newHw
                delete sceneOptions.publicSubnetId
             }
            if (this.type === 4) { // 渗透赛不需要传递这些参数，避免扰乱后端逻辑
                delete sceneOptions.hwChangeIp
                delete sceneOptions.hwDeployMode
                delete sceneOptions.spareEnvNum
                delete sceneOptions.targetCount
                delete sceneOptions.teamPublicSubnetId
                sceneOptions.vmInEnable = this.vmInEnable
                if(this.vmTeamOrPerson === 'person'){
                    sceneOptions.vmTeamOrPerson = 'person'
                    sceneOptions.noNeedProjectService = true
                }
            }
             if(this.type === 5 && this.hwType == 1) {
                 sceneOptions.teamIpCount=parseInt(extIObj.teamIpCount)
                 sceneOptions.teamPublicSubnetId  = extIObj.teamPublicSubnetId
             }
             if(this.type === 5 && ([1,2,4].includes(this.hwType)) && this.vmTeamOrPerson === 'person'){
                sceneOptions.vmTeamOrPerson = 'person'
                sceneOptions.noNeedProjectService = true
             }
             if(this.type === 5 && this.hwType === 0 && this.vmTeamOrPerson === 'person'){
                sceneOptions.terminalEnable = true
                sceneOptions.noNeedProjectService = true
             }
             if(this.type==5&&this.hwType!=3){
                sceneOptions.vmInEnable = this.vmInEnable
             }
            if(this.type === 5 && this.hwType == 2 || this.type === 5 && this.hwType == 4) {
                sceneOptions.publicSubnetId = JSON.parse(this.drillInfo.extension).publicSubnetId
                sceneOptions.vmInEnable = this.vmInEnable
                sceneOptions.newHw = 'vpn'
            }
            console.log('=========',this.type,this.checkTeamList);
            sceneOptions.teams = this.checkTeamList.map(item => {
                return {
                    addUserEnable: false,
                    id: item.id,
                    name: item.name,
                    teamMenberNumber: this.type === 5 ? item.userIdList.length : undefined, // 护网演练需要设置成员数量
                    teamMenbers: this.type === 5 ? item.userNameList : undefined, // 护网演练需要设置团队成员名称列表
                    players:item.userIdList.map((userId, index)=>({
                        userId,
                        username: item.userNameList[index]
                    }))
                }
            })
            sceneOptions.contestPapers = this.checkQuestionList.filter(item => item.needEnv === 'true').map(item => {
                return {
                    flavorRef: item.flavorRef,
                    imageRef: item.imageRef,
                    name: item.name
                }
            })
            if(this.type == 5 && JSON.parse(this.drillInfo.extension).needEnv === false) {
                sceneOptions.needEnv = false
            }
            let api;
            api = quickCreateContest;
            if(this.type === 5 && this.hwType === 0 && this.vmTeamOrPerson === 'person'){
                api = quickCreateContestMacth
            }
            api(sceneOptions).then(data => {
                if (data.code === 1) { // 快速构建成功，将工程信息与竞赛绑定
                    data = data.data || {}
                    let { projectId, projectName } = data
                    let param = {
                        id: this.drillInfo.id,
                        projectId,
                        projectName
                    }
                    modifyScene(param.id, param).then(data => { // 绑定快速构建场后的工程信息与竞赛、演练的关系
                        if (data.code !== 1) {
                            this.$Message.warning(data.message)
                            this.saveLoading = false
                        } else {
                            this.hide()
                            this.vmInEnable = false
                            this.$Message.info('快速构建成功')
                            this.$emit('getCompetList')
                            if (this.type === 4) { // 渗透演练需要额外绑定竞赛与题目关系
                                let params = this.checkQuestionList.map(item => {
                                    return {
                                        "description": item.data.description, //描述
                                        "externalIp": "", // 对外ip
                                        "externalPort": "", // 对外端口
                                        "name": item.data.name, //题目显示名称
                                        "port": item.data.port,
                                        "projectId": projectId,
                                        "questionId": item.data.id, //题目id
                                        "sceneId": this.drillInfo.id,
                                        "score": item.data.score,
                                        "type": item.needEnv === 'true' ? 1 : 2, // 1虚拟机靶标 2分析靶标
                                        "visibility": 0, //可见性：是否可见- 0.不可见 1可见
                                        "flagPath": item.data.flagPath,
                                        "servicePort": item.data.port,
                                        "isNeedSubmitFlag": String(item.data.submitFlag),
                                        "isFixedFileFlag": String(item.data.flagType),
                                        "flag": item.data.flagTxt,
                                        "imageId": item.data.imageId,
                                        "imageName": item.data.imageName
                                    }
                                })
                                batchAddTarget(params).then(({ code, message }) => {
                                    if (code !== 1) {
                                        this.$Message.warning(message)
                                        this.saveLoading = false
                                    }
                                }).catch(() => {
                                    this.saveLoading = false
                                    this.$Message.error('绑定题目场景关系异常')
                                })
                            }
                        }
                    }).catch(() => {
                        this.$Message.error('修改场景异常')
                    })
                } else {
                    if(data.message){
                        this.$Message.warning(data.message);
                    }
                }
                this.saveLoading = false
            }).catch(() => {
                this.saveLoading = false
                this.$Message.error('快速构建异常')
            })
        },
        // 选择题目，同步更新镜像、配额、前缀信息
        changeQuestion(value) {
            if (!value) {
                this.questionForm.image = ''
                this.questionForm.flavor = ''
                this.questionForm.prefix = ''
            } else {
                let question = this.questionList.find(item => item.id === value) || {}
                this.questionForm.image = question.imageId
                this.questionForm.flavor = question.flavorRef
                this.questionForm.prefix = question.name
            }
        },
        challsChangeSize(val) {
            this.questionParams.pageSize = val
            this.queryCtfList()
        },
        challsPageNum(val) {
            this.questionParams.pageIndex = val
            this.queryCtfList()
        },
        challsSizeNum(val) {
            this.questionParams.pageSize = val
            this.queryCtfList()
        },
        // 删除选中的题目
        removeQuestion(selection,row){
            let chaIdList = []
            // 将选中的题目设置为未选中状态
            if(!row){ // 全选
                this.questionList.forEach(ques => { // 
                    ques._checked = false;
                    chaIdList.push(ques.chaId)
                })
            }else{
                this.questionList = this.questionList.map(item => {
                    item.chaId === row.chaId ? item._checked = false : ''
                    return item
                })
                chaIdList.push(row.chaId)
            }
            // 拷贝两份数据做批量操作，最终赋值一次
            let checkQuestionList = [...this.checkQuestionList]
            chaIdList.forEach(id => {
                let delChallIndex = checkQuestionList.findIndex(item=>item.chaId===id)
                if(delChallIndex>=0) checkQuestionList.splice(delChallIndex, 1);
            })
            this.checkQuestionList = checkQuestionList
        },
        // 查询题目列表
        queryCtfList() {
            queryCtfList({
                needEnv: this.questionParams.needEnv === 'all' ? ''  : this.questionParams.needEnv,
                name: this.questionParams.name,
                applicationList: [0,2], //竞赛和通用
                category: this.questionParams.category === 'all' ? ''  : this.questionParams.category,
                flagType: this.questionParams.flagType === 'all' ? ''  : this.questionParams.flagType,
                otherFlagType: 2
            },{
                pageIndex: this.questionParams.pageIndex,
                pageSize: this.questionParams.pageSize,
            }).then(({ code, message, data }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                data.items.forEach(item=>{
                    item._disabled = item.answers.length > 1 || item.category === '安全运维'
                    this.$set(item,'chaId',item.id)
                    // this.$set(item,'_checked',false)
                    if(item.imageId){
                        item.needEnv = "true"
                    }else{
                        item.needEnv = "false"
                    }
                    if(item.matchMode  === '3'){ //问答题禁止选择
                        item._disabled = true
                    }
                    item._checked = (this.checkQuestionList.find(subItem => subItem.chaId === item.chaId)) !== undefined
                })
                this.questionList = data.items
                this.questionTotal = data.total
            }).catch(() => {
                this.$Message.error('获取题目异常')
            })
        },
        // 清空搜索条件并查询数据
        resetParams() {
            this.pageIndex = 1
            this.pageSize = 10
            this.teamName = ''
            this.getTeamList()
            this.questionParams = {
                pageIndex: 1, // 当前页
                pageSize: 10, // 分页大小
                name: '',
                needEnv: 'all',
                category: 'all',
                flagType: 'all'
            }
            this.queryCtfList()
        },
        // 添加接入机器/添加题目，需求变更，该方法不再使用
        // commitSelectData(type) {
        //     let isQuestuin = type === 'question'
        //     let formName = isQuestuin ? 'questionForm' : 'accessMachineForm'
        //     this.$refs[formName].validate(valid => {
        //         if (valid) {
        //             let currentImageName = "", currentFlavorName = ""
        //             if (isQuestuin) {
        //                 let currentImage = this.imageList.find(item => item.id === this.questionForm.image)
        //                 currentImageName = currentImage && currentImage.imagename
        //                 let currentFlavor = this.flavorList.find(item => item.id === this.questionForm.flavor)
        //                 currentFlavorName = currentFlavor && currentFlavor.flavorname
        //                 let currentTargetName = ""
        //                 let currentTarget = this.questionList.find(item => item.chaId === this.questionForm.question)
        //                 currentTargetName = currentTarget && currentTarget.name
        //                 this.checkQuestionList.push({
        //                     currentTargetName,
        //                     currentImageName,
        //                     currentFlavorName,
        //                     prefix: this.questionForm.prefix,
        //                     type: 'SERVER',
        //                     numbers: this.questionForm.numbers,
        //                     questionType: '题目',
        //                     flavorRef: this.questionForm.flavor,
        //                     imageRef: this.questionForm.image,
        //                     id: `${this.questionForm.image},${this.questionForm.flavor},${this.questionForm.question}`
        //                 })
        //             } else {
        //                 let currentImage = this.imageList.find(item => item.id === this.accessMachineForm.image)
        //                 currentImageName = currentImage && currentImage.imagename
        //                 let currentFlavor = this.flavorList.find(item => item.id === this.accessMachineForm.flavor)
        //                 currentFlavorName = currentFlavor && currentFlavor.flavorname
        //                 this.accessMachineList.push({
        //                     name: `${currentImageName}/${currentFlavorName}/${this.accessMachineForm.prefix}/CLIENT/${this.accessMachineForm.numbers}/手动配置`,
        //                     id: `${this.accessMachineForm.image},${this.accessMachineForm.flavor}`
        //                 })
        //             }
        //             this.$nextTick(() => {
        //                 this.$refs[formName].resetFields()
        //             })
        //         }
        //     })
        // },
        // 查询镜像详情，用于比较配额是否可使用
        getImageDetail(imageId){
            if(!imageId){
                return;
            }
            getDetailByID(imageId).then(({ data }) => {
                let { code, attribute, message } = data
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.currentImageInfo = attribute.imageDate
            })
        },
        // 查询镜像列表
        getImageList(){
            const obj = {}
            const search = {
                pageIndex:1,
                pageSize:9999
            }
            getallImage(obj,search).then(({ code, message, data }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.imageList = data.items
            }).catch(() => {
                this.$Message.error('获取镜像异常')
            })
        },
        // 查询所有的配额
        getAllFlavor() {
            const search = {
                pageIndex:1,
                pageSize:9999
            }
            getallFlavor(search).then(({ code, message, data }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.flavorList = data.items
            }).catch(() => {
                this.$Message.error('获取配额异常')
            })
        },
        // 防抖封装，团队名改变时，延迟更新列表数据
        getDataBounce: debounce(function() {
            this.teamsPageNum(1)
        }),
        // 修改分页大小
        teamsChangeSize(val) {
            this.pageSize = val
            this.getTeamList()
        },
        // 修改当前页
        teamsPageNum(val) {
            this.pageIndex = val
            this.getTeamList()
        },
        teamsSizeNum(val){
            this.pageSize = val
            this.getTeamList()
        },
        // 删除选中的团队
        removeTeam(selection,row){
            let teamIdList = []
            if(!row){ // 通过全选来删除团队
                this.teamList.forEach(team => {
                    team._checked = false;
                    teamIdList.push(team.id)
                })
            }else{ // 删除单个团队
                let listTeam = this.teamList.filter(item => item.id == row.id);
                if(listTeam.length > 0){
                    listTeam[0]._checked = false;
                }
                teamIdList.push(row.id)
            }
            let teamList = [...this.checkTeamList]
            teamIdList.forEach(id => {
                    // 删除tags数据
                let delteamIndex = teamList.findIndex(items =>items.id===id)
                if(delteamIndex>=0) teamList.splice(delteamIndex, 1);
            })
            this.checkTeamList = teamList
        },
        // 删除添加的接入机器/题目
        removeSelectData(type, index) {
            if (type === 'question') {
                this.checkQuestionList.splice(index, 1)
            } else {
                this.accessMachineList.splice(index, 1)
            }
        },
         // 选中团队，并判断团队是否存在相同的成员
        selectTeam(selection, row){
            this.checkTeamList.push(row)
        },
        // 判断是否有重复的成员，去重后长度不一致，则存在相同成员
        haveDuplicateMembers(allSelUserIds) {
            return [...new Set(allSelUserIds)].length != allSelUserIds.length
        },
        // 获取团队列表，级联查询团队下的所有用户，用于成员同名筛查
        getTeamList() {
            this.loadingTable = true
            getGroupHasUsers({
                pageIndex: this.pageIndex,
                pageSize: this.pageSize,
                name: this.teamName
            }).then(({data:{ code, message, data }}) => {
                if (code !== 1) {
                    this.loadingTable = false
                    this.$Message.warning(message)
                    return
                }
                // let teamList = []
                let selTeamIds = this.checkTeamList.map(team => team.id);
                this.teamList = data.items.map(team => {
                    let userNameList = []
                    let userIdList = []
                    team.userList.forEach(user => {
                        userNameList.push(user.username)
                        userIdList.push(user.id)
                    })
                    team.userNameList = userNameList
                    team.userIdList = userIdList
                    team.userNum = userIdList.length;
                    team._disabled = userIdList.length === 0 ? true : false
                    // 获取团队下的用户数据
                    // await getExperGroupsUsers(team.id).then(data => {
                    //     if (data.code == 1) {
                    //         let userNameList = []
                    //         let userIdList = []
                    //         data.data.forEach(user => {
                    //             userNameList.push(user.userName)
                    //             userIdList.push(user.userId)
                    //         })
                    //         team.userList = userNameList.join(',')
                    //         team.userIdList = userIdList
                    //         team.userNum = data.data.length;
                    //         team._disabled = this.type === 5 ? userIdList.length === 0 : false
                    //     }
                    // });
                    team._checked = selTeamIds.includes(team.id)
                    return team
                    // teamList.push(team)
                })
                // this.teamList = teamList
                this.teamTotal = data.total
            }).catch((error) => {
                this.$Message.error('获取团队异常')
            }).finally(() => {
                this.loadingTable = false
            }) 
        },
        // 模态框隐藏时，重置相关数据
        visibleChange(flag) {
            if (!flag) {
                this.vmInEnable = false
                this.allowVirtualAccess = false
                this.saveLoading = false
                this.$refs.accessMachineForm && this.$refs.accessMachineForm.resetFields()
                this.$refs.questionForm && this.$refs.questionForm.resetFields()
                this.$refs.accessMachineForm && this.$refs.accessMachineForm.resetFields()
                this.noTeam = false
                this.selectQuestions = []
                this.accessMachineList = []
                this.checkTeamList = []
                this.questionList = this.questionList.map(item => {
                    item._checked = false
                    return item
                })
                this.$nextTick(() => { // 数据更新后再设置这几个值，避免被watch中的回调改写
                    this.showDuplicateNameTip = false
                    this.noQuestion = false
                    this.noAccessMachine = false
                    this.noTeam = false
                })
                this.resetParams()
            } else { // 关闭模态框时，延迟使按钮点击，避免多次提交
                setTimeout(() => {
                    this.saveLoading = false
                }, 1000)
            }
        },
        // 显示快速构建模态框
        show(obj) {
            this.showQuickCreateModal = true
            this.vmInEnable = this.type == 4 ? true : false
            this.vmTeamOrPerson = 'team'
            this.drillInfo = obj || {}
            this.getTeamList()
            if (this.type === 4) {
                this.queryCtfList()
            }
        },
        // 隐藏快速构建模态框
        hide() {
            this.showQuickCreateModal = false
            this.vmInEnable = false
        }
    }
}
</script>

<style scoped>
    .error-text {
        display: block;
        color: #ed4014;
        flex: 1;
    }
    .mb40 {
        margin-bottom: 40px;
    }
    .mt30-right {
        float: right; 
        margin-top: -30px;
    }
    .select-tag {
        display: flex;
        max-width: 100%;
        width: max-content;
        align-items: center;
        float: left;
    }
    .select-tag >>> .ivu-tag-text {
        width: 100%;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        display: inline-block;
    }
    .select-tag >>> .ivu-tag-dot-inner {
        flex-shrink: 0;
        top: 0;
    }
    .bold {
        font-weight: bold;
        display: flex;
        align-items: center;
        height: fit-content;
    }
    .bold >>> .ivu-tag {
        margin: 0 4px;
    }
    .tag-list {
        margin: 10px 0;
    }
</style>